/* ---------------- IndexedDB 初始化 ---------------- */
let db;                                               // 全局唯一
const request = indexedDB.open('WebDB', 1);

request.onupgradeneeded = e => {
  db = e.target.result;

  // 如果第一次创建，生成各对象仓库
  const stores = [
    { name: 'courses',          indexes:[['userId']] },
    { name: 'comments',         indexes:[['courseId'],['userid']] },
    { name: 'notes',            indexes:[['courseId'],['userid']] },
    { name: 'assignments',      indexes:[['courseId']] },
    { name: 'coursewares',      indexes:[['name'],['userid'],['courseId']] },
    { name: 'homework',         indexes:[['studentId']] },
    { name: 'ref_student_course',indexes:[['courseId'],['studentId']] }
  ];

  stores.forEach(s=>{
    if(!db.objectStoreNames.contains(s.name)){
      const os = db.createObjectStore(s.name,{keyPath:'id',autoIncrement:true});
      s.indexes.forEach(idx=>os.createIndex(idx[0], idx[0], {unique:false}));
    }
  });
};

request.onsuccess = e => {
  db = e.target.result;
  loadCourses();                 // 首屏渲染推荐课程
};

request.onerror = e => console.error('IndexedDB error:', e.target.errorCode);

/* ---------------- 推荐课程区 ---------------- */
// function loadCourses(){
//   if(!db) return;                                 // 还未初始化
//   const tx = db.transaction('courses','readonly');
//   tx.objectStore('courses').getAll().onsuccess = e=>{
//     const courses = e.target.result.sort((a,b)=>b.recommend-a.recommend);
//     const list    = document.getElementById('course-list');
//     list.innerHTML = '';
//     courses.forEach(c=>{
//       const card = document.createElement('div');
//       card.className = 'course-card';
//       card.innerHTML = `
//         <input type="checkbox" class="ui-checkbox" data-id="${c.id}" ${c.recommend?'checked':''}>
//         <img src="${(c.carouselImages&&c.carouselImages[0])||'../Homepage/images/default-course.jpg'}" alt="${c.title}" class="course-img">
//         <div class="course-info">
//            <h3>${c.title}</h3>
//            <p>${c.description||''}</p>
//         </div>`;
//       list.appendChild(card);
//     });
//   };
// }

// 设为推荐 / 取消推荐
// document.getElementById('recommend-btn').addEventListener('click',()=>{
//   if(!db) return;
//   const tx  = db.transaction('courses','readwrite');
//   const os  = tx.objectStore('courses');
//   os.getAll().onsuccess = e=>{
//     e.target.result.forEach(course=>{
//       course.recommend = document.querySelector(`input[data-id="${course.id}"]`).checked;
//       os.put(course);
//     });
//   };
//   tx.oncomplete = ()=>{ alert('Setting successful'); loadCourses(); };
// });

/* ---------------- 账号管理区 ---------------- */
function loadAccounts() {
  console.log('[DEBUG] Loading account information ..');
  const tbody = document.getElementById('account-tbody');
  if (!tbody) return;

  tbody.innerHTML = '';

  const accounts = [];
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);

    // 跳过非用户数据的 key
    if (key === 'token' || key === 'admin') continue;

    try {
      const data = JSON.parse(localStorage.getItem(key) || '{}');

      // 如果不是用户对象则跳过
      if (!data.avatar || !data.identity || !data.userid) continue;

      accounts.push({
        id: data.userid,
        avatar: data.avatar,
        name: data.username || data.userid,
        role: data.identity,
        status: data.status !== false
      });
    } catch (e) {
      console.warn(`[Skip invalid data] LocalStorage [${key}] parsing failed:`, e);
    }
  }

  accounts.forEach(user => {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td><img src="${user.avatar}" width="40"></td>
      <td>${user.name}</td>
      <td>${user.role === 'teacher' ? 'teacher' : 'student'}</td>
      <td>${user.status ? 'normal' : 'Frozen'}</td>
      <td>
      <button class="freeze-btn ${user.status ? 'freeze' : 'unfreeze'}" onclick="toggleStatus('${user.id}', this)">
  ${user.status ? 'freeze' : 'thaw'}
</button>

      </td>
    `;
    tbody.appendChild(tr);
  });
}
function toggleStatus(userid) {
  const userData = JSON.parse(localStorage.getItem(userid));
  if (!userData) return alert('User data does not exist');

  const confirmText = userData.status ? 'Are you sure to freeze this account?' : 'Are you sure to unfreeze this account?';
  if (!confirm(confirmText)) return;

  userData.status = !userData.status;
  localStorage.setItem(userid, JSON.stringify(userData));
  loadAccounts();
}




// 冻结 / 解冻按钮委托
document.addEventListener('click', e => {
  const btn = e.target.closest('.freeze-btn');
  if (!btn) return;

  const id = btn.dataset.uid;
  if (!id) return;

  let obj;
  try {
    obj = JSON.parse(localStorage.getItem(id));
  } catch (error) {
    console.error('Failed to parse user data:', error);
    return;
  }

  // 切换状态
  obj.status = !obj.status;
  localStorage.setItem(id, JSON.stringify(obj));

  // 更新按钮状态和文本
  btn.classList.remove('freeze', 'unfreeze');
  if (obj.status) {
    btn.classList.add('freeze');
    btn.textContent = 'freeze';
  } else {
    btn.classList.add('unfreeze');
    btn.textContent = 'thaw';
  }
  console.log(`Button click: User ID=${id}, new status=${obj. status}`);


  // 更新“状态”单元格显示
  const tdStatus = btn.closest('tr').querySelector('td:nth-child(4)');
  if (tdStatus) {
    tdStatus.textContent = obj.status ? 'normal' : 'Frozen';
  }
});



/* ---------------- 侧边栏切换 ---------------- */
document.addEventListener('DOMContentLoaded', () => {
  showContent('accounts');
});

function showContent(id) {
  document.querySelectorAll('.content > section').forEach(section => {
    section.style.display = section.id === id ? 'block' : 'none';
  });
  document.querySelectorAll('.sidebar-item').forEach(item => {
    item.classList.toggle('active', item.getAttribute('href').substring(1) === id);
  });
  if (id === 'accounts') loadAccounts();
}

// 侧边栏点击事件
document.querySelectorAll('.sidebar-item').forEach(a=>{
  a.addEventListener('click',e=>{
    e.preventDefault();
    showContent(a.getAttribute('href').substring(1));
  });
});

/* ---------------- 页面首次加载 ---------------- */
document.addEventListener('DOMContentLoaded', ()=>{
  // 侧边栏头像 / 名称
  const uid = localStorage.getItem('token');
  if(uid){
    const me = JSON.parse(localStorage.getItem(uid));
    document.getElementById('sidebar-avatar').src  = me.avatar||'';
    document.getElementById('sidebar-username').innerText = me.username||'administrators';
  }

 showContent('accounts');        // 默认页
});
